<?php
class TemplateLanguage
{
    const LNG_EXTENSION = '.xml';

    /**
     * Returns associative array with texts for specified template. It does checking current site language.
     * @param string $templateFileName is an relative path to template.
     * @param string $lng Template language
     * @param TemplateEngine $tmpl Template engine
     * @return array
     */
    public static function GetTemplateLngVars( $templateFileName, $lng = null, TemplateEngine $tmpl = null )
    {
        $lngVars = array();

        $lngFilePath = self::GetTemplateLngFilePath( $templateFileName );

        if ( file_exists( $lngFilePath ) )
        {
            $xml = @file_get_contents( $lngFilePath );

            // process tokens
            if ( $tmpl )
            {
                $substitutions = new TemplateSubstitutions($tmpl);
                $xml = $substitutions->Process( $xml );
            }

            $doc = Util::CreateXmlDocument( $xml, false );

            if ( !is_null( $doc ) )
            {
                $xpath = new XPathHelper( $doc );
                $nodes = $xpath->GetNodes( '/texts/*' );
                if ( isset( $nodes ) )
                {
                    foreach ( $nodes as $node )
                    {
                        $varName = $node->tagName;
                        $varValue = $node->nodeValue;
                        $lngVars[$varName] = $varValue;
                    }
                }
            }
        }

        return $lngVars;
    }

    /**
     * It returns lng file path for current site language if it exists, or lng file path for EN.
     * @param string $templateFileName
     * @return string
     */
    private static function GetTemplateLngFilePath( $templateFileName, $lng = null )
    {
        $language = $lng ? $lng : Core::GetLanguage();

        $templateFileExtension = pathinfo( $templateFileName, PATHINFO_EXTENSION );
        $relativeDir = pathinfo( $templateFileName, PATHINFO_DIRNAME );
        $lngFileName = basename( $templateFileName, ".{$templateFileExtension}" ) . self::LNG_EXTENSION;

        $lngFilePath = "";
        if ( $relativeDir != "." && $relativeDir != ".." && $relativeDir != "\\" )
        {
            $lngFilePath = LNG_DIR . "{$language}/{$relativeDir}/{$lngFileName}";
        }
        else
        {
            $lngFilePath = LNG_DIR . "{$language}/{$lngFileName}";
        }

        $lngFilePath = str_replace( "//", "/", $lngFilePath );

        if ( !file_exists( $lngFilePath ) && $language != SiteLanguage::EN )
        {
            $lngFilePath = LNG_DIR . SiteLanguage::EN . "/" . $relativeDir . "/" . $lngFileName;
        }

        return $lngFilePath;
    }
}
?>